<template>
	<view class="">
		<view class="file_selection">
			<view v-for="(imgs, index) in staticList" :key="index" class="file_selection_list">
				<image :src="imgs.url" class="file_selection_con" @click="prviewImage(imgs, index)"></image>
				<view class="file_selection_del icon-del-box" @click="delFile(index)">
					<view class="icon-del"></view>
					<view class="icon-del rotate"></view>
				</view>
			</view>

			<view class="file-picker__box" :style="boxStyle">
				<view class="file-picker__box-content is-add" :style="borderStyle" @click="chooseImg">
					<slot>
						<view class="icon-add"></view>
						<view class="icon-add rotate"></view>
					</slot>
				</view>
			</view>
		</view>

		<!-- 文件选择视图 start -->
		<uni-popup class="file-modal-box" ref="fileListPopup" type="center">
			<view class="file-modal file-modal-pc">
				<!-- 渲染资源列表 -->
				<unicloud-db
					ref="udb"
					@load="onqueryload"
					collection="files_list"
					:options="options"
					:where="where"
					field="_id,file,createTime"
					page-data="replace"
					:orderby="orderby"
					:getcount="true"
					:page-size="options.pageSize"
					:page-current="options.pageCurrent"
					v-slot:default="{ data, pagination, loading, error }"
				>
					<view style="display: flex;flex-direction: row;">
						<input class="uni-search" type="text" v-model="query" @confirm="search" placeholder="请输入搜索内容" />
						<button class="uni-button" type="default" size="mini" @click="search">搜索</button>
						<button class="uni-button" type="primary" size="mini" @click="chooseimgupload">新增</button>
						<button class="uni-button" type="default" size="mini" @click="delTable" :disabled="!selectedIndexs.length">批量删除</button>
					</view>

					<uni-table class="file_list_tab" :loading="loading" :emptyText="error.message || '没有更多数据'" type="selection" @selection-change="selectionChange">
						<view class="file_list_con">
							<uni-tr class="file_list_all_sel">
								<uni-th align="center">全选</uni-th>
								<!-- <uni-th align="center">文件大小</uni-th> -->
							</uni-tr>
							<uni-tr v-for="(item, index) in data" :key="index" class="s_list">
								<view class="file_list_con_view">
									<uni-td align="center" class="user_name_ava">
										<view v-if="item.file.fileType == 'video'">
											<!-- <image v-if="item.file" :src="item.file.url" class="file_list_con_img"  @click="prviewImages(item,index,data)"></image> -->
											<video id="myVideo" :src="item.file.url" @error="videoErrorCallback" controls style="width: 10vw; height:10vw"></video>
										</view>
										<view v-else-if="item.file.fileType == 'image'">
											<image
												v-if="item.file"
												:src="item.file.url"
												class="file_list_con_img"
												@click="prviewImages(item, index, data)"
												style="width: 100%;"
												mode="aspectFill"
											></image>
										</view>
										<view v-else><audio :src="item.file.url" :name="item.file.name" controls style="width: 10vw; height:10vw;overflow: hidden;"></audio></view>
										<view>
											<view class="file_list_con_name">{{ item.file.name }}</view>
											<view class="file_list_con_size">{{ item.size }}</view>
											<view class="file_list_con_time"><uni-dateformat :date="item.createTime" :threshold="[0, 0]" /></view>
										</view>
									</uni-td>

									<uni-td align="center">
										<view class="uni-group"><button @click="confirmDelete(item)" class="uni-button" size="mini" type="warn">删除</button></view>
									</uni-td>
								</view>
							</uni-tr>
						</view>
					</uni-table>
					<view class="uni-pagination-box">
						<uni-pagination show-icon :page-size="pagination.size" v-model="pagination.current" :total="pagination.count" @change="onPageChanged" />
					</view>
				</unicloud-db>

				<button type="primary" size="mini" class="add_btn_b_r" @click="confirmChoose">确认使用</button>
			</view>
		</uni-popup>
		<!-- 文件选择视图 end -->

		<!-- 上传文件视图 start -->
		<uni-popup class="upfile-modal-box" ref="temfilePopup" type="center">
			<view class="upfile-modal upfile-modal-pc">
				<!-- <Icons :tag="false" :fix-window="false"/> -->
				<uni-file-picker
					title="上传"
					:file-mediatype="file_type"
					ref="files"
					:auto-upload="false"
					:limit="up_limit"
					mode="grid"
					@select="selectImgdone"
					@progress="imguploading"
					@success="upyunimgdata"
					return-type="array"
					style="width: 600rpx;"
				/>
				<button type="primary" size="mini" class="add_btn_b_r" @click="startuploadImg">上传</button>
			</view>
		</uni-popup>

		<!-- 上传文件视图 end -->
	</view>
</template>

<script>
/*参数说明
 *
 * 1、staticList：当前已使用资源的数组
 * 2、use_limit：可使用资源的数量限制，默认：5；此处需要配合被使用数据表字段的最大值限制：schema的maxLength
 * 3、up_limit：单次上传最大数量，默认：9
 * 4、file_type：资源类型过滤：all、imgae、video
 *
 */
const db = uniCloud.database();
// 表查询配置
const dbOrderBy = 'createTime desc'; // 排序字段
const dbSearchFields = ['file.name']; // 支持模糊搜索的字段列表
// 分页配置
const pageSize = 5;
const pageCurrent = 1;

export default {
	props: {
		title: String,
		staticList: {
			type: Array,
			default() {
				return [];
			}
		},
		use_limit: {
			type: Number,
			default: 5
		},
		up_limit: {
			type: Number,
			default: 9
		},
		file_type: {
			type: String,
			default: 'image'
		}
	},
	// 参数
	data() {
		return {
			// 获取资源列表的参数
			cloudfileList: [],
			query: '',
			where: '',
			orderby: dbOrderBy,
			options: {
				pageSize,
				pageCurrent
			},
			selectedIndexs: [], //批量选中的项
			formDatalist: {},
			selectdData: null
		};
	},
	// 页面计算
	computed: {},
	//组件被创建执行
	created() {
		if (this.file_type == 'all') {
			this.where = '';
		} else {
			this.where = "file.fileType=='" + this.file_type + "'";
		}
	},
	methods: {
		onqueryload: function(data) {
			this.cloudfileList = data;
			for (var i = 0; i < data.length; i++) {
				let item = data[i];
				item.size = this.renderSize(item.file.size);
			}
		},
		//确认使用图至业务。调用父组件selectedfile对应的的函数，并传值
		confirmChoose: function(e) {
			this.$refs.fileListPopup.close();
			this.$emit('selectedfile', this.$refs.udb.dataList[this.selectedIndexs]);
		},

		// 多选，选择后输出
		selectionChange: function(e) {
			this.selectedIndexs = e.detail.index;
		},
		// 多选处理参数id
		selectedItems: function() {
			this.selectdData = this.$refs.udb.dataList;
			var dataList = this.$refs.udb.dataList;
			var IdList = this.selectedIndexs.map(i => dataList[i]._id);
			var UrlList = this.selectedIndexs.map(i => dataList[i].file.url);
			return { IdList, UrlList };
		},
		//批量删除
		delTable: function() {
			const new_dataList = this.selectedItems();
			this.$refs.udb.remove(new_dataList.IdList, {
				confirmTitle: '提示', // 确认框标题
				confirmContent: '是否删除该资源', // 确认框内容
				success: res => {
					// 删除成功后的回调
					const { code, message } = res;
					//删除对应云存储
					uniCloud
						.callFunction({
							name: 'files',
							data: {
								filesList: new_dataList.UrlList
							}
						})
						.then(res => {
							uni.showToast({
								title: '删除成功'
							});
						});
				},
				fail: err => {
					// 删除失败后的回调
					const { message } = err;
				},
				complete: () => {
					// 完成后的回调
				}
			});
		},
		//确认删除云端资源
		confirmDelete: function(item) {
			this.$refs.udb.remove(item._id, {
				confirmTitle: '提示', // 确认框标题
				confirmContent: '是否删除该资源', // 确认框内容
				success: res => {
					// 删除成功后的回调
					const { code, message } = res;
					//删除对应云存储
					uniCloud
						.callFunction({
							name: 'files',
							data: {
								filesList: [item.file.url]
							}
						})
						.then(res => {
							uni.showToast({
								title: '删除成功'
							});
						});
				},
				fail: err => {
					// 删除失败后的回调
					const { message } = err;
				},
				complete: () => {
					// 完成后的回调
				}
			});
		},

		delFile: function(index) {
			console.log(index);
			// this.$emit('delFile', index)
			this.staticList.splice(index, 1);
		},
		/*
		 *搜索
		 */
		getWhere: function() {
			const query = this.query.trim();
			if (!query) {
				return '';
			}
			const queryRe = new RegExp(query, 'i');
			return dbSearchFields.map(name => queryRe + '.test(' + name + ')').join(' || ');
		},
		search: function(e) {
			const newWhere = this.getWhere();
			const isSameWhere = newWhere === this.where;
			this.where = newWhere;
			if (isSameWhere) {
				// 相同条件时，手动强制刷新
				this.loadData();
			}
		},
		loadData: function(clear = true) {
			this.$refs.udb.loadData({
				clear
			});
		},
		//选择图片
		chooseImg: function() {
			if (this.staticList.length >= this.use_limit) {
				uni.showModal({
					title: '提示',
					content: '当前字段不允许使用大于' + this.use_limit + '个资源文件',
					showCancel: false
				});
				return;
			} else {
				this.$refs.fileListPopup.open();
			}
		},
		//翻页
		onPageChanged: function(e) {
			this.$refs.udb.loadData({
				current: e.current
			});
		},
		// 添加文件图标的样式
		boxStyle: function() {
			const { width = 'auto', height = 'auto' } = this.styles;
			let obj = {};
			if (height === 'auto') {
				if (width !== 'auto') {
					obj.height = this.value2px(width);
					obj['padding-top'] = 0;
				} else {
					obj.height = 0;
				}
			} else {
				obj.height = this.value2px(height);
				obj['padding-top'] = 0;
			}

			if (width === 'auto') {
				if (height !== 'auto') {
					obj.width = this.value2px(height);
				} else {
					obj.width = '33.3%';
				}
			} else {
				obj.width = this.value2px(width);
			}

			let classles = '';
			for (let i in obj) {
				classles += `${i}:${obj[i]};`;
			}
			return classles;
		},
		borderStyle: function() {
			let { border } = this.styles;
			let obj = {};
			if (typeof border === 'boolean') {
				obj.border = border ? '1px #eee solid' : 'none';
			} else {
				let width = (border && border.width) || 1;
				width = this.value2px(width);
				let radius = (border && border.radius) || 5;
				radius = this.value2px(radius);
				obj = {
					'border-width': width,
					'border-style': (border && border.style) || 'solid',
					'border-color': (border && border.color) || '#eee',
					'border-radius': radius
				};
			}
			let classles = '';
			for (let i in obj) {
				classles += `${i}:${obj[i]};`;
			}
			return classles;
		},
		/*
		 * 以下为上传文件至云端的相关函数
		 *
		 * */
		//开始选择图片，打开图片选择器模态框
		chooseimgupload: function() {
			this.$refs.fileListPopup.close();
			this.$refs.temfilePopup.open();
			//选择图片
			// uni.chooseImage({
			// 	// count: 1,
			// 	success: (res) => {
			// 		console.log(res)
			// 		this.tem_uploadImg = res.tempFiles
			// 	}
			// })
		},
		//图片选择已完成，执行此函数：获取已上传图片的名称和大小
		selectImgdone: function(e) {
			e.tempFiles.map(item => {
				// console.log(item.name)
				// console.log(item.size)
			});
		},
		//确认上传本地图片至云存储
		startuploadImg: function() {
			this.$refs.files.upload();
			uni.showLoading({
				title: '上传中...'
			});
		},
		imguploading: function(e) {},
		filterFile: function(file_type) {
			if (file_type == 'mp3' || file_type == 'mpeg' || file_type == 'wma') {
				return 'audio';
			} else if (file_type == 'mp4') {
				return 'video';
			} else {
				return 'image';
			}
		},
		//上传云存储后，执行此函数：保存至数据库
		upyunimgdata: function(e) {
			const db = uniCloud.database();
			const filesList = db.collection('files_list');
			//e.tempFiles，array， 是上传云存储后返回的文件数据，可以直接存储数据库
			//逐个保存
			e.tempFiles.map(item => {
				console.log(item);
				if (this.file_type == 'all') {
					item.fileType = this.filterFile(item.extname);
				}
				filesList
					.add({
						file: item,
						createTime: Date.now()
					})
					.then(res => {})
					.catch(err => {
						console.log(err);
					});
			});
			uni.hideLoading();
			this.$refs.temfilePopup.close();
			this.$refs.fileListPopup.open();
			// setTimeout(() => uni.navigateBack(), 500)
		},
		//预览图片
		prviewImage: function(img, index) {
			let urls = [];
			if (Number(this.limit) === 1 && this.disablePreview && !this.disabled) {
				this.$emit('choose');
			}
			if (this.disablePreview) return;
			this.staticList.forEach(i => {
				urls.push(i.url);
			});

			uni.previewImage({
				urls: urls,
				current: index
			});
		},
		//预览图片
		prviewImages: function(img, index, lists) {
			lists = JSON.parse(JSON.stringify(lists));
			let urls = [];
			if (Number(this.limit) === 1 && this.disablePreview && !this.disabled) {
				this.$emit('choose');
			}
			if (this.disablePreview) return;
			lists.forEach(i => {
				urls.push(i.file.url);
			});

			uni.previewImage({
				urls: urls,
				current: index
			});
		},
		//格式化文件大小可读性
		renderSize: function(value) {
			if (null == value || value == '') {
				return '0 Bytes';
			}
			var unitArr = new Array('Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');
			var index = 0;
			var srcsize = parseFloat(value);
			index = Math.floor(Math.log(srcsize) / Math.log(1024));
			var size = srcsize / Math.pow(1024, index);
			size = size.toFixed(2); //保留的小数位数
			// console.log(size+unitArr[index])
			return size + unitArr[index];
		},
		videoErrorCallback: function(e) {
			console.log(e);
		}
	}
};
</script>

<style>
.file_selection {
	display: flex;
	flex-direction: row;
}
.file_selection_list {
	margin: 0px 20rpx;
	position: relative;
}
.file_selection_con {
	width: 230rpx;
	height: 230rpx;
}
.file_selection_del {
	position: absolute;
	top: 0px;
	right: 0px;
	cursor: pointer;
}

.file-picker__box {
	position: relative;
	flex: 0 0 33.3%;
	width: 230rpx;
	height: 230rpx;
	padding-top: 10rpx;
	box-sizing: border-box;
}

.file-picker__box-content {
	position: absolute;
	top: 0;
	right: 0;
	bottom: 0;
	left: 0;
	margin: 5px;
	border: 1px #eee solid;
	border-radius: 8px;
	overflow: hidden;
}
.is-add {
	display: flex;
	align-items: center;
	justify-content: center;
}

.icon-add {
	width: 50px;
	height: 5px;
	background-color: #f1f1f1;
	border-radius: 10rpx;
}
.add_btn_t_r {
	position: absolute;
	top: 20rpx;
	right: 20rpx;
}
.add_btn_b_r {
	position: absolute;
	bottom: 20rpx;
	right: 20rpx;
}
.file_list_tab {
	height: 80%;
	margin-top: 50rpx;
}
.file_list_con {
	display: flex;
	flex-flow: row wrap;
	width: 70vw;
	padding-top: 80rpx;
	overflow: auto;
}
.file_list_con_view {
	width: 12vw;
	height: 100%;
	/* position: relative; */
	display: flex;
	flex-direction: column;
}
.file_list_all_sel {
	position: absolute;
	top: 0rpx;
	padding: 0px 10px;
	display: none;
}
.file_list_con_img {
	width: 300rpx;
	height: 300rpx;
}
.file_list_con_name {
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
	direction: rtl;
	width: 300rpx;
}
.file_list_con_size {
	color: #999999;
	font-size: 12px;
	margin: 10rpx 0px;
}
.file_list_con_time {
	color: #999999;
	font-size: 12px;
}
.rotate {
	position: absolute;
	transform: rotate(90deg);
}

.file-modal,
.upfile-modal {
	width: 350px;
	background-color: #fff;
	height: auto;
	padding: 50rpx;
	border-radius: 10rpx;
}

@media screen and (min-width: 768px) {
	.file-modal-pc {
		width: 70vw;
		height: 33vw;
		display: flex;
		flex-direction: row;
	}
	.upfile-modal-pc {
		width: 50vw;
		height: 15vw;
		display: flex;
		flex-direction: row;
	}
}
.uni-table-td {
	border-bottom: none;
}
.s_list {
	display: flex;
	flex: 1;
	flex-direction: column;
	margin: 0px 33rpx;
	position: relative;
}
.icon-del-box {
	display: flex;
	align-items: center;
	justify-content: center;
	position: absolute;
	top: 5px;
	right: 5px;
	height: 26px;
	width: 26px;
	border-radius: 50%;
	background-color: rgba(0, 0, 0, 0.5);
	z-index: 2;
	transform: rotate(-45deg);
}

.icon-del {
	width: 15px;
	height: 2px;
	background-color: #fff;
	border-radius: 2px;
}
</style>
